<!DOCTYPE html>
<html xmlns:wb="http://open.weibo.com/wb">
<head>
  <meta charset="utf-8">
  <script src="https://cdn.jsdelivr.net/gh/Sanarous/files@1.13/js/linkcard.js"></script>
  <script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?fc9a8559a133f4d8ce784d69d6337bb0";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>

  
  <title>springcloud微服务六：声明式服务调用Feign | 涂宗勋的博客</title>
  <meta name="baidu-site-verification" content="o8pWlgAEZ7" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="在有了eureka服务注册中心、ribbon负载均衡及服务消费、hystrix断路器三部分之后，其实在某种程度上就应该能够创建一个基本的spring cloud微服务应用了，只不过这种应用无论是代码层面还是架构层面都还有一定的缺陷。从代码层面来讲，ribbon和hystrix是一个标准化springcloud应用最基本的模块，通常也都是同时出现的，因此为了简化开发，有一个更高层次的工具来对他们进行">
<meta property="og:type" content="article">
<meta property="og:title" content="springcloud微服务六：声明式服务调用Feign">
<meta property="og:url" content="https://tuzongxun.gitee.io/2018/09/09/springcloud6/index.html">
<meta property="og:site_name" content="涂宗勋的博客">
<meta property="og:description" content="在有了eureka服务注册中心、ribbon负载均衡及服务消费、hystrix断路器三部分之后，其实在某种程度上就应该能够创建一个基本的spring cloud微服务应用了，只不过这种应用无论是代码层面还是架构层面都还有一定的缺陷。从代码层面来讲，ribbon和hystrix是一个标准化springcloud应用最基本的模块，通常也都是同时出现的，因此为了简化开发，有一个更高层次的工具来对他们进行">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-09-09T07:09:42.000Z">
<meta property="article:modified_time" content="2019-10-17T03:29:30.162Z">
<meta property="article:author" content="涂宗勋">
<meta property="article:tag" content="java">
<meta property="article:tag" content="springcloud">
<meta name="twitter:card" content="summary">
  
  
    <link rel="icon" href="/images/touxiang.png">
  
  
    
  
  
<link rel="stylesheet" href="/tzxblog/css/style.css">

  

<meta name="generator" content="Hexo 4.2.1"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <script src="https://tjs.sjs.sinajs.cn/open/api/js/wb.js" type="text/javascript" charset="utf-8"></script>
  <script src="https://cdn.jsdelivr.net/gh/Sanarous/files@1.13/js/linkcard.js"></script>
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    
    <div id="header-inner" class="inner">
      <nav id="sub-nav">
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://tuzongxun.gitee.io"></form>
      </div>
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/tzxblog/">首页</a>
        
          <a class="main-nav-link" href="/tzxblog/shuoshuo/">说说</a>
        
          <a class="main-nav-link" href="/tzxblog/archives/">归档</a>
        
          <a class="main-nav-link" href="/tzxblog/collections/">导航</a>
        
          <a class="main-nav-link" href="/tzxblog/download/">资源</a>
        
          <a class="main-nav-link" href="/tzxblog/about/">简历</a>
        
      </nav>
      
    </div>
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/tzxblog/" id="logo">涂宗勋的博客</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/tzxblog/" id="subtitle">java程序员，现居武汉，CSDN博客https://blog.csdn.net/tuzongxun</a>&nbsp;&nbsp;&nbsp;&nbsp;
		  <!--<span id="busuanzi_container_site_pv">【本站累计访问量:<span id="busuanzi_value_site_pv"></span>】</span>-->
        </h2>
		
      
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-springcloud6" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/tzxblog/2018/09/09/springcloud6/" class="article-date">
  <time datetime="2018-09-09T07:09:42.000Z" itemprop="datePublished">2018-09-09</time>
</a>
    
  <div class="article-category">
    <a class="article-category-link" href="/tzxblog/categories/springcloud/">springcloud</a>
  </div>

</span>
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      springcloud微服务六：声明式服务调用Feign
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <!-- Table of Contents -->
        
        <p>在有了eureka服务注册中心、ribbon负载均衡及服务消费、hystrix断路器三部分之后，其实在某种程度上就应该能够创建一个基本的spring cloud微服务应用了，只不过这种应用无论是代码层面还是架构层面都还有一定的缺陷。<br>从代码层面来讲，ribbon和hystrix是一个标准化springcloud应用最基本的模块，通常也都是同时出现的，因此为了简化开发，有一个更高层次的工具来对他们进行了封装整合，这就是Feign。<br>feign在整合了这两者强大功能的同时，还提供了一种声明式的web服务客户端定义方式及可插拔式的注解，同时支持spring mvc的注解。<br>在ribbon和hystrix的基础上，feign看起来就比较简单。</p>
<a id="more"></a>

<h1 id="一、基本使用"><a href="#一、基本使用" class="headerlink" title="一、基本使用"></a>一、基本使用</h1><h2 id="maven依赖"><a href="#maven依赖" class="headerlink" title="maven依赖"></a>maven依赖</h2><p>需要在eureka依赖的基础上再引入对feign的依赖：</p>
<pre>
&lt;dependency>
        &lt;groupId>org.springframework.cloud&lt;/groupId>
        &lt;artifactId>spring-cloud-starter-feign&lt;/artifactId>
&lt;/dependency>
</pre>

<p>application.properties基本配置</p>
<pre>
服务名
spring.application.name=feign-client
端口
server.port=9099
允许ip访问
eureka.instance.prefer-ip-address=true
指定注册中心地址
eureka.client.serviceUrl.defaultZone=http://localhost:10010/eureka/
</pre>

<p>启动类注解，在项目启动类加入如下三个注解，就可以使用feign：</p>
<pre>
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
</pre>

<p>在加入了上边注解的前提下，就可以编写feign声明式调用服务的接口：</p>
<pre>
@FeignClient("client")
public interface FeignService {
    @RequestMapping("/hello")
    String sayHello();
}
</pre>

<p>其中@FeignClient后的client即之前写好的eureka服务的服务名，接口里的方法定义和client里controller类中的定义一摸一样，区别就是没有具体的实现，也不需要具体的实现。<br>当我们在当前系统中调用FeignService .sayHello方法的时候，就会去服务名为client的服务中调用具体的同名同定义的方法。<br>如果服务名为client的有多个，那么由于feign内部整合的是ribbon，所以实际上是使用ribbon的默认负载均衡策略进行选择，也就是线性轮询。<br>如果有用过webservice和hessian这类远程调用服务技术的，应该会发现这里的写法和他们如出一辙。</p>
<h1 id="二、优化"><a href="#二、优化" class="headerlink" title="二、优化"></a>二、优化</h1><h2 id="增加fallback"><a href="#增加fallback" class="headerlink" title="增加fallback"></a>增加fallback</h2><p>上边的代码就可以基本实现feign的功能，可以正常调用eureka了，但是和单独使用ribbon一样，当服务故障的时候，系统就会出现问题。所以一般@FeignClient这里可能会写成下边这样：</p>
<pre>
@FeignClient(name = "client", fallback = ClientFallBack.class)
</pre>

<p>name后边的client和上边的直接一个字符串声明等同，后边的ballback指定当服务出现故障时服务降级之后的处理类。<br>这个类是一个很简单的java类，需要继承FeignService接口，并实现接口中的方法。这个方法在有的地方被称作本地方法，当服务降级后就会调用这个方法里写的逻辑。</p>
<pre>
public class ClientFallBack implements FeignService {
    @Override
    public String sayHello() {
        return "say hello";
    }
}
</pre>

<h2 id="捕获服务异常"><a href="#捕获服务异常" class="headerlink" title="捕获服务异常"></a>捕获服务异常</h2><p>上边的实现，可以一定程度上保证服务降级后继续一定的逻辑处理，但是如果需要在降级后的逻辑中捕获降级前的异常信息，就需要把fallback改成fallbackFactory，这个降级处理类就可以写成下边这样：</p>
<pre>
@Component
public class ClientFallBackFactory implements FallbackFactory<FeignService> {
    @Override
    public FeignService create(Throwable cause) {
        return new FeignService() {
            @Override
            public String sayHello() {
                System.out.println(cause.getMessage());
                return "say hello";
            }
        };
    }
}
</pre>
      
    </div>
    <footer class="article-footer">
      <a data-url="https://tuzongxun.gitee.io/2018/09/09/springcloud6/" data-id="ckxn7cxjc005pkcvhecyh4lcb" class="article-share-link">分享</a>
      
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tzxblog/tags/java/" rel="tag">java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tzxblog/tags/springcloud/" rel="tag">springcloud</a></li></ul>

    </footer>
  </div>
  
    
  <div class="comments" id="comments">
    
     
       
       
      
      
	 
  </div>
 
    
 
<script src="/tzxblog/jquery/jquery.min.js"></script>

  <div id="random_posts">
    <h2>推荐文章</h2>
    <div class="random_posts_ul">
      <script>
          var random_count =5
          var site = {BASE_URI:'/tzxblog/'};
          function load_random_posts(obj) {
              var arr=site.posts;
              if (!obj) return;
              // var count = $(obj).attr('data-count') || 6;
              for (var i, tmp, n = arr.length; n; i = Math.floor(Math.random() * n), tmp = arr[--n], arr[n] = arr[i], arr[i] = tmp);
              arr = arr.slice(0, random_count);
              var html = '<ul>';
            
              for(var j=0;j<arr.length;j++){
                var item=arr[j];
                html += '<li><strong>' + 
                item.date + ':&nbsp;&nbsp;<a href="' + (site.BASE_URI+item.uri) + '">' + 
                (item.title || item.uri) + '</a></strong>';
                if(item.excerpt){
                  html +='<div class="post-excerpt">'+item.excerpt+'</div>';
                }
                html +='</li>';
                
              }
              $(obj).html(html + '</ul>');
          }
          $('.random_posts_ul').each(function () {
              var c = this;
              if (!site.posts || !site.posts.length){
                  $.getJSON(site.BASE_URI + 'js/posts.js',function(json){site.posts = json;load_random_posts(c)});
              } 
               else{
                load_random_posts(c);
              }
          });
      </script>
    </div>
  </div>

	
<nav id="article-nav">
  
    <a href="/tzxblog/2018/09/15/springcloud7/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">上一篇</strong>
      <div class="article-nav-title">
        
          springcloud微服务七：网关zuul
        
      </div>
    </a>
  
  
    <a href="/tzxblog/2018/09/03/springcloud5/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">下一篇</strong>
      <div class="article-nav-title">springcloud微服务五：客户端负载均衡ribbon</div>
    </a>
  
</nav>

  
</article>

</section>
           
    <aside id="sidebar">
  
    <!--微信公众号二维码-->


  
    

  
    
  
    
    <div class="widget-wrap">
    
      <div class="widget" id="toc-widget-fixed">
      
        <strong class="toc-title">文章目录</strong>
        <div class="toc-widget-list">
              <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#一、基本使用"><span class="toc-number">1.</span> <span class="toc-text">一、基本使用</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#maven依赖"><span class="toc-number">1.1.</span> <span class="toc-text">maven依赖</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#二、优化"><span class="toc-number">2.</span> <span class="toc-text">二、优化</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#增加fallback"><span class="toc-number">2.1.</span> <span class="toc-text">增加fallback</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#捕获服务异常"><span class="toc-number">2.2.</span> <span class="toc-text">捕获服务异常</span></a></li></ol></li></ol>
          </div>
      </div>
    </div>

  
    

  
    
  
    
  
    

  
</aside>

      </div>
      <footer id="footer">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  
  <div class="outer">
    <div id="footer-left">
      &copy; 2016 - 2021 涂宗勋&nbsp; <a href="https://beian.miit.gov.cn/#/Integrated/recordQuery" target="_blank" rel="noopener">鄂ICP备20000142号</a> |&nbsp;&nbsp;
      主题 <a href="https://github.com/giscafer/hexo-theme-cafe/" target="_blank">Cafe</a>&nbsp;|&nbsp;&nbsp;
	  <span id="busuanzi_container_site_uv">本站有效访客数<span id="busuanzi_value_site_uv"></span>人</span>
	  <span id="busuanzi_container_site_pv" >| 总访问量 <span id="busuanzi_value_site_pv"></span> 次 </span>
	  <div style="width:300px;margin:0 auto; padding:20px 0;"><a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=42010302002171"style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img src="http://www.tzxcode.cn/wp-content/uploads/2020/01/备案图标.png" style="float:left;"/><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">鄂公网安备 42010302002171号</p></a>
		 	</div>
    </div>
     <div id="footer-right">
      联系方式&nbsp;|&nbsp;1160569243@qq.com
    </div>
	
  </div>
</footer>
 
<script src="/tzxblog/jquery/jquery.min.js"></script>

 <script>
$(document).ready(function() {

    var int = setInterval(fixCount, 50);  // 50ms周期检测函数
    var countOffset = 20000;  // 初始化首次数据

    function fixCount() {            
       if (document.getElementById("busuanzi_container_site_pv").style.display != "none")
        {
            $("#busuanzi_value_site_pv").html(parseInt($("#busuanzi_value_site_pv").html()) + countOffset); 
            clearInterval(int);
        }                  
        if ($("#busuanzi_container_site_pv").css("display") != "none")
        {
            $("#busuanzi_value_site_uv").html(parseInt($("#busuanzi_value_site_uv").html()) + countOffset); // 加上初始数据 
            clearInterval(int); // 停止检测
        }  
    }
       	
});
</script> 
    </div>
    <nav id="mobile-nav">
  
    <a href="/tzxblog/" class="mobile-nav-link">首页</a>
  
    <a href="/tzxblog/shuoshuo/" class="mobile-nav-link">说说</a>
  
    <a href="/tzxblog/archives/" class="mobile-nav-link">归档</a>
  
    <a href="/tzxblog/collections/" class="mobile-nav-link">导航</a>
  
    <a href="/tzxblog/download/" class="mobile-nav-link">资源</a>
  
    <a href="/tzxblog/about/" class="mobile-nav-link">简历</a>
  
</nav>
    <img class="back-to-top-btn" src="/images/fly-to-top.png"/>
<script>
// Elevator script included on the page, already.
window.onload = function() {
  var elevator = new Elevator({
    selector:'.back-to-top-btn',
    element: document.querySelector('.back-to-top-btn'),
    duration: 1000 // milliseconds
  });
}
</script>
      

  

  







<!-- author:forvoid begin -->
<!-- author:forvoid begin -->

<!-- author:forvoid end -->

<!-- author:forvoid end -->



 
<script src="/tzxblog/js/is.js"></script>



  
<link rel="stylesheet" href="/tzxblog/fancybox/jquery.fancybox.css">

  
<script src="/tzxblog/fancybox/jquery.fancybox.pack.js"></script>




<script src="/tzxblog/js/script.js"></script>


<script src="/tzxblog/js/elevator.js"></script>

  </div>
</body>
</html>